import React, { useState, useEffect, useRef } from 'react';
import { SafeAreaView, StyleSheet, TouchableOpacity, Text, Button, View, Image, FlatList, ScrollView, Dimensions, RefreshControl } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { ActionSheet } from 'antd-mobile-rn';
import { Camera } from "expo-camera";
import { Video } from "expo-av";
import { useFocusEffect } from '@react-navigation/native';

import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from '../../api/axios';
import { useAuth, baseURL } from '../../context/AuthProvider';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;
// const baseURL = 'http://192.168.253.1:8080'

const WINDOW_HEIGHT = Dimensions.get("window").height;

const closeButtonSize = Math.floor(WINDOW_HEIGHT * 0.032);
const captureSize = Math.floor(WINDOW_HEIGHT * 0.09);
const add = (m) => { return m < 10 ? + m : m }
//将时间戳转为普通格式
const fortime = (shijianchuo) => {
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add(m) + '-' + add(d) + ' ' + add(h) + ':' + add(mm) + ':' + add(s);
}
// 生长日志
const Page2 = ({ value }) => {
    const [hasPermission, setHasPermission] = useState(null);
    const { navigation } = value
    const { id } = value
    console.log(999999999998);
    console.log(id);
    // const { recordlist } = value
    // const [imageUrl, setImageUrl] = useState('')
    const [imageUrl, setImageUrl] = useState([])
    const [isShow, setShow] = useState(false)
    const [showCamera, setShowCamera] = useState(1)
    const [clicked, setClicked] = useState('none')
    const [cameraType, setCameraType] = useState(Camera.Constants.Type.back);
    const [isPreview, setIsPreview] = useState(false);
    const [isCameraReady, setIsCameraReady] = useState(false);
    const cameraRef = useRef();
    const [takePic, setTakePic] = useState('')
    const [refreshing, setRefreshing] = useState(false);
    const [page, setPage] = useState(1)
    const { list } = value
    const {setList} = value
    const [recordlist, setRecordlist] = useState(list?list:[])
    const [eff, setEff] = useState(0)
    const [myid, setMyid] = useState('')
    const { user } = useAuth()
    var arr = []

    useEffect(() => {
        console.log(1111111);
        (async () => {
            const { status } = await Camera.requestPermissionsAsync();
            setHasPermission(status === "granted");
        })();
        AsyncStorage.getItem('mycropsid').then(data => {
            if (data[0]) {
                console.log(data);
                setMyid(JSON.parse(data)[0].id)
                axios.post('/recordlist/getrecordlist', { id: JSON.parse(data)[0].id }).then(res => {
                    console.log(res.data);
                    setList(res.data)
                    // setRefreshing(false)
                })
            }
        })
    }, []);

    useEffect(()=>{
        console.log(2222);
        AsyncStorage.getItem('mycropsid').then(data => {
            if (data[0]) {
                console.log(data);
                axios.post('/recordlist/getrecordlist', { id: JSON.parse(data)[0].id }).then(res => {
                    console.log(res.data);
                    let m = res.data
                    setList(res.data)
                    setRefreshing(false)
                })
            }
        })
    }, [eff]);
    useFocusEffect(React.useCallback(() => {
        // AsyncStorage.getItem('list').then(data => {
        //     if (data) {
        //         setRecordlist(JSON.parse(data))
        //     }
        // })
        setRefreshing(false)
        setEff(eff+1)
        setList(list)
        // setRecordlist([])
        // AsyncStorage.getItem('mycropsid').then(data => {
        //     if (data[0]) {
        //         console.log(data);
        //         axios.post('/recordlist/getrecordlist', { id: JSON.parse(data)[0].id }).then(res => {
        //             console.log(res.data);
        //             setRecordlist(res.data)
        //         })
        //     }
        // })
        setIsPreview(false)
    }, []))
    const onCameraReady = () => {
        setIsCameraReady(true);
    };
    // 点击拍照
    const takePicture = async () => {
        if (cameraRef.current) {
            const options = { quality: 0.5, base64: true, skipProcessing: true };
            const data = await cameraRef.current.takePictureAsync(options);
            const source = data.uri;
            if (source) {
                await cameraRef.current.pausePreview();
                setIsPreview(true);
                setTakePic(source)
            }
        }
    };

    // 翻转摄像头
    const switchCamera = () => {
        if (isPreview) {
            return;
        }
        setCameraType((prevCameraType) =>
            prevCameraType === Camera.Constants.Type.back
                ? Camera.Constants.Type.front
                : Camera.Constants.Type.back
        );
    };

    // 拍照点击×事件
    const cancelPreview = async () => {
        await cameraRef.current.resumePreview();
        setIsPreview(false);
        setShow(false)
    };
    // 拍照点击√事件
    const okPreview = async () => {
        setShow(!isShow)
        setIsPreview(false);
        AsyncStorage.getItem('mycropsid').then(data => {
            if (data) {
                console.log(JSON.parse(data));
                console.log(23456);
                console.log((JSON.parse(data)[0]));
                navigation.navigate('cropdetail', { imageUrl: [takePic], id: JSON.parse(data)[0].id, cropsid: JSON.parse(data)[1].cropsid })
            }
        })
        // navigation.navigate('cropdetail', { imageUrl: arr, id: Number(data), cropsid: recordlist[0].cropsid })
    }

    // 拍照页面上方×和√，点击×取消返回生长日志页，点击√进入detail页面
    const renderCancelPreviewButton = () => (
        <View style={{ justifyContent: 'space-between', flexDirection: 'row', width: '100%' }}>
            <TouchableOpacity onPress={cancelPreview} style={styles.closeButton}>
                <View style={[styles.closeCross, { transform: [{ rotate: "45deg" }] }]} />
                <View
                    style={[styles.closeCross, { transform: [{ rotate: "-45deg" }] }]}
                />
            </TouchableOpacity>
            <TouchableOpacity onPress={okPreview} style={[styles.okButton]}>
                <Text>√</Text>
            </TouchableOpacity>
        </View>
    );

    // 拍照页面底部，翻转按钮以及拍照按钮
    const renderCaptureControl = () => (
        <View style={styles.control}>
            <TouchableOpacity disabled={!isCameraReady} onPress={switchCamera}>
                <Text style={styles.text}>{"翻转"}</Text>
            </TouchableOpacity>
            <TouchableOpacity
                activeOpacity={0.7}
                disabled={!isCameraReady}
                // onLongPress={recordVideo}
                // onPressOut={stopVideoRecording}
                onPress={takePicture}
                style={styles.capture}
            />
        </View>
    );

    if (hasPermission === null) {
        return <View />;
    }

    if (hasPermission === false) {
        return <Text style={styles.text}>No access to camera</Text>;
    }
    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            // allowsEditing: true,
            // aspect: [3, 3],
            quality: 1,
            useNativeDriver: true,
            allowsMultipleSelection: true
        });
        if (!result.canceled) {
            for (let i = 0; i < result.assets.length; i++) {
                arr.push(result.assets[i].uri)
            }
            AsyncStorage.getItem('mycropsid').then(data => {
                console.log(arr);
                console.log(Number(data));
                console.log(8888888);
                if (data) {
                    console.log(data);
                    console.log(JSON.parse(data)[0]);
                    console.log(JSON.parse(data)[1].cropsid);
                    console.log(777777);
                    console.log(arr);
                    console.log(6666666);
                    navigation.navigate('cropdetail', { imageUrl: arr, id: JSON.parse(data)[0].id, cropsid: JSON.parse(data)[1].cropsid })
                }
            })
            setIsPreview(false);
            setTimeout(() => {
                arr = []
            }, 10)
        }
    }
    const showActionSheet = () => {
        const BUTTONS = [
            <Text>拍照</Text>,
            <Text onPress={pickImage} >从相册选择</Text>,
            '取消',
        ]
        ActionSheet.showActionSheetWithOptions(
            {
                options: BUTTONS,
                cancelButtonIndex: 2,
                useNativeDriver: true
            },
            (buttonIndex) => {
                setClicked(BUTTONS[buttonIndex])
                if (buttonIndex == 0) {
                    // pickImage()
                    setShowCamera(2)
                    setShow(!isShow)
                } else if (buttonIndex == 1) {
                    pickImage()
                }
            },
        )
    }
    const onEnd = () => {
        setPage(page + 1)
    }
    const onRefresh = () => {
        setRefreshing(true);
        setPage(1);
        axios.post('/recordlist/getrecordlist', { id: id }).then(res => {
            console.log(res.data);
            // setRecordlist(res.data)
            setRefreshing(false);
        })
    }

    const renderItem = ({ item }) => (
        <View style={{ flexDirection: 'row', height: 90, margin: 18 }}>
            <View style={{ width: 80, justifyContent: 'flex-start' }}>
                <View style={{ alignItems: 'flex-start', height: 35 }}>
                    <Text style={{ fontSize: 16, marginLeft: 5 }}>{fortime(item.recorddate).split('-')[0]}年</Text>
                    <Text style={{ fontSize: 14, marginLeft: 5 }}>{fortime(item.recorddate).split('-')[1]}月{(fortime(item.recorddate).split('-')[2]).split(' ')[0]}日</Text>
                </View>
            </View>
            {
                item.imgs.length > 0 ?
                    <TouchableOpacity style={{ flexDirection: 'row' }} onPress={() => navigation.navigate('cropimgs', { item: item })}>
                        <Image source={{ uri: item.imgs[0].url }}
                            style={{ width: 90, height: 90, resizeMode: 'contain' }}
                        />
                        <View style={{ justifyContent: 'space-between', marginLeft: 20 }}>
                            <Text style={{ flexWrap: 'wrap', width: 250 }}>{item.recordtext}</Text>
                            <Text style={{ fontSize: 12 }}>共{item.imgs.length}张</Text>
                        </View>
                    </TouchableOpacity>
                    :
                    <TouchableOpacity style={{ flexDirection: 'row' }}>
                        <View style={{ justifyContent: 'space-between', marginLeft: 20 }}>
                            <Text style={{ flexWrap: 'wrap' }}>{item.recordtext}</Text>
                        </View>
                    </TouchableOpacity>
            }
        </View>
    )
    const load = ()=>{
        setEff(eff+1)
    }
    return (
        <View>
            {
                isShow ?
                    <SafeAreaView style={[{ width: screenW, height: screenH - 80 }]}>
                        <Camera
                            ref={cameraRef}
                            style={[styles.container, { width: screenW, height: '100%' }]}
                            type={cameraType}
                            flashMode={Camera.Constants.FlashMode.on}
                            onCameraReady={onCameraReady}
                            onMountError={(error) => {
                                console.log("cammera error", error);
                            }}
                        />
                        <View style={styles.container}>
                            {isPreview && renderCancelPreviewButton()}
                            {!isPreview && renderCaptureControl()}
                        </View>
                    </SafeAreaView>
                    :
                    <ScrollView style={{ width: screenW, backgroundColor: '#fff' }}
                        refreshControl={
                            <RefreshControl
                                refreshing={refreshing}
                                onRefresh={() => {
                                    setRefreshing(true)
                                    setEff(eff+1);
                                    load()
                                }}
                                tintColor='black'
                                title={refreshing ? '刷新中' : '下拉刷新'}
                                titleColor='black'
                                colors={['white', 'gray', 'black']}
                                progressBackgroundColor='lightblue'
                            />
                        }
                    >
                        {/* <View> */}
                        <Image source={require('../../../images/mine/topbg.jpg')} style={{ width: '100%', resizeMode: 'contain', height: 173, marginTop: -6 }} />
                        {/* </View> */}
                        <View style={{ flexDirection: 'row', justifyContent: 'flex-end', marginTop: -46.5, marginRight: 10 }}>
                            <Image source={(user&&user.avatar) ? { uri: user.avatar } : require('../../../images/mine/avatar.jpg')}
                                style={{
                                    width: 88, height: 88, borderRadius: 50, borderWidth: 5, borderColor: '#fff'
                                }} />
                        </View>
                        <View>
                            <View style={{ flexDirection: 'row', height: 90, margin: 18 }}>
                                <View style={{ width: 80, justifyContent: 'flex-start' }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'flex-end', height: 26 }}>
                                        <Text style={{ fontSize: 18 }}>今天</Text>
                                    </View>
                                </View>
                                <View style={{ flexDirection: 'row' }}>
                                    <TouchableOpacity onPress={()=>{if(myid==''){alert("请先选择作物再进行上传哦")} else if(!user){alert("请先登录")} else{showActionSheet()}}}>
                                        <Image source={require('../../../images/records/camera.jpg')}
                                            style={{ width: 90, height: 90, resizeMode: 'contain' }}
                                        />
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>

                        <View>
                            {
                                list.map(item => {
                                    return <View style={{ flexDirection: 'row', height: 90, margin: 18 }}>
                                        <View style={{ width: 80, justifyContent: 'flex-start' }}>
                                            <View style={{ alignItems: 'flex-start', height: 35 }}>
                                                <Text style={{ fontSize: 16, marginLeft: 5 }}>{fortime(item.recorddate).split('-')[0]}年</Text>
                                                <Text style={{ fontSize: 14, marginLeft: 5 }}>{fortime(item.recorddate).split('-')[1]}月{(fortime(item.recorddate).split('-')[2]).split(' ')[0]}日</Text>
                                            </View>
                                        </View>
                                        {
                                            item.imgs.length > 0 ?
                                                <TouchableOpacity style={{ flexDirection: 'row' }} onPress={() => navigation.navigate('cropimgs', { item: item })}>
                                                    <Image source={{ uri: baseURL +item.imgs[0].url }}
                                                        style={{ width: 90, height: 90, resizeMode: 'contain' }}
                                                    />
                                                    <View style={{ justifyContent: 'space-between', marginLeft: 20 }}>
                                                        <Text style={{ flexWrap: 'wrap', width: 250 }}>{item.recordtext}</Text>
                                                        <Text style={{ fontSize: 12 }}>共{item.imgs.length}张</Text>
                                                    </View>
                                                </TouchableOpacity>
                                                :
                                                <TouchableOpacity style={{ flexDirection: 'row' }}>
                                                    <View style={{ justifyContent: 'space-between', marginLeft: 20 }}>
                                                        <Text style={{ flexWrap: 'wrap' }}>{item.recordtext}</Text>
                                                    </View>
                                                </TouchableOpacity>
                                        }
                                    </View>
                                })
                            }
                            {/* <View><Text style={{ fontSize: 20, marginLeft: 18 }}>2022年</Text></View>
                            <View style={{ flexDirection: 'row', height: 90, margin: 18 }}>
                                <View style={{ width: 80, justifyContent: 'flex-start' }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'flex-end', height: 26 }}>
                                        <Text style={{ fontSize: 18 }}>25</Text>
                                        <Text style={{ fontSize: 12, marginLeft: 5 }}>4月</Text>
                                    </View>
                                </View>
                                <View style={{ flexDirection: 'row' }}>
                                    <Image source={require('../../../images/records/camera.jpg')}
                                        style={{ width: 90, height: 90, resizeMode: 'contain' }}
                                    />
                                    <View style={{ justifyContent: 'space-between', marginLeft: 20 }}>
                                        <Text>11111111</Text>
                                        <Text style={{ fontSize: 12 }}>共2张</Text>
                                    </View>
                                </View>
                            </View> */}

                        </View>
                    </ScrollView>
            }
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject
    },
    closeButton: {
        // position: "absolute",
        top: 35,
        left: 15,
        height: closeButtonSize,
        width: closeButtonSize,
        borderRadius: Math.floor(closeButtonSize / 2),
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#c4c5c4",
        opacity: 0.7,
        zIndex: 2,
    },
    okButton: {
        // position: "absolute",
        top: 35,
        right: 15,
        height: closeButtonSize,
        width: closeButtonSize,
        borderRadius: Math.floor(closeButtonSize / 2),
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#c4c5c4",
        opacity: 0.7,
        zIndex: 2,
    },
    media: {
        ...StyleSheet.absoluteFillObject,
    },
    closeCross: {
        width: "68%",
        height: 1,
        backgroundColor: "black",
    },
    control: {
        position: "absolute",
        flexDirection: "row",
        bottom: 38,
        width: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    capture: {
        backgroundColor: "#f5f6f5",
        borderRadius: 5,
        height: captureSize,
        width: captureSize,
        borderRadius: Math.floor(captureSize / 2),
        marginHorizontal: 31,
    },
    recordIndicatorContainer: {
        flexDirection: "row",
        position: "absolute",
        top: 25,
        alignSelf: "center",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "transparent",
        opacity: 0.7,
    },
    recordTitle: {
        fontSize: 14,
        color: "#ffffff",
        textAlign: "center",
    },
    recordDot: {
        borderRadius: 3,
        height: 6,
        width: 6,
        backgroundColor: "#ff0000",
        marginHorizontal: 5,
    },
    text: {
        color: "#fff",
    },
});
export default Page2; 